package com.pet.system.security.jwt;

import com.pet.system.utils.SpringContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * jwt 验证过滤器
 *
 * @author Centaurea
 */
public class JwtAuthFilter extends BasicHttpAuthenticationFilter {

  @Override
  protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
    return !StringUtils.isEmpty(getToken((HttpServletRequest) request));
  }

  @Override
  protected boolean isAccessAllowed(
      ServletRequest request, ServletResponse response, Object mappedValue) {
    if (isLoginAttempt(request, response)) {
      try {
        executeLogin(request, response);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return true;
  }

  @Override
  protected boolean executeLogin(ServletRequest request, ServletResponse response)
      throws Exception {
    JwtToken token = new JwtToken(getToken((HttpServletRequest) request));
    getSubject(request, response).login(token);
    return true;
  }

  private String getToken(HttpServletRequest request) {
    JwtProperties jwtConfig = SpringContextUtil.getBean(JwtProperties.class);
    String token = request.getHeader(jwtConfig.getHeaderName());
    if (StringUtils.isEmpty(token)) {
      token = request.getParameter(jwtConfig.getHeaderName());
    }
    return token;
  }
}
